<template>
  <div class="animal-detail-page" v-if="animal">
    <el-card class="animal-card">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-image :src="animal.imageUrl" fit="cover" style="width: 100%; height: 400px; border-radius: 8px;" />
        </el-col>
        <el-col :span="14">
          <div class="animal-info">
            <div class="header-with-status">
              <h1>{{ animal.name }}</h1>
              <el-tag :type="saleStatusInfo.type" size="large" effect="dark">
                {{ saleStatusInfo.text }}
              </el-tag>
            </div>
            <p class="description">{{ animal.description }}</p>
            <el-divider />
            <div class="info-grid">
              <p><strong>品种:</strong> {{ animal.breed }}</p>
              <p><strong>年龄:</strong> {{ animal.age }} 岁</p>
              <p><strong>性别:</strong> {{ animal.gender === 0 ? '公' : '母' }}</p>
              <p><strong>健康状况:</strong> <el-tag type="success">{{ animal.healthStatus }}</el-tag></p>
            </div>
            <div class="price">
              <span>价格: </span>
              <span class="amount">¥{{ animal.price }}</span>
            </div>
            <div class="actions">
              <el-button
                  type="danger"
                  size="large"
                  @click="handleApply"
                  :disabled="animal.saleStatus === 1"
              >
                {{ animal.saleStatus === 1 ? '已售出' : '申请预定' }}
              </el-button>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
  <div v-else class="loading">
    <el-skeleton :rows="15" animated />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getAnimalById } from '@/api/animal.js';
import { useUserStore } from '../stores/userStore';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

const animal = ref(null);
const loading = ref(true);

const saleStatusMap = {
  0: { text: '在售', type: 'success' },
  1: { text: '已售出', type: 'info' },
  2: { text: '已被预定', type: 'warning' },
};

const saleStatusInfo = computed(() => {
  if (!animal.value) return {};
  return saleStatusMap[animal.value.saleStatus] || { text: '未知', type: 'info' };
});

const fetchAnimalDetail = async () => {
  loading.value = true;
  try {
    const res = await getAnimalById(route.params.id);
    if (res) {
      animal.value = res;
    } else {
      ElMessage.error(res.message || '获取宠物详情失败');
    }
  } catch (error) {
    ElMessage.error('网络请求失败');
  } finally {
    loading.value = false;
  }
};

const handleApply = () => {
  if (!userStore.isAuthenticated) {
    ElMessageBox.confirm('您需要登录后才能申请，是否现在登录？', '请先登录', {
      confirmButtonText: '去登录',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => router.push('/login'));
    return;
  }

  if (animal.value.saleStatus === 1) {
    ElMessage.warning('抱歉，这只宠物已被买走啦！');
    return;
  }

  // 直接跳转到创建订单页（即预定申请页）
  router.push({
    name: 'CreateOrder',
    query: { animalId: animal.value.id }
  });
};

onMounted(fetchAnimalDetail);
</script>

<style scoped>
.header-with-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}
h1 { margin: 0; }
.description { color: #606266; }
.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px 20px;
  margin-bottom: 25px;
}
.price {
  margin-bottom: 25px;
  font-size: 1.2em;
  color: #f56c6c;
}
.price .amount {
  font-size: 2em;
  font-weight: bold;
}
.loading {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}
</style>
